import { Module, OnModuleInit } from '@nestjs/common';
import { HttpModule } from '@nestjs/axios';
import { ConfigModule } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { CopilotConfig } from '../database/entities/copilot-config.entity';
import { CopilotRequestLog } from '../database/entities/copilot-request-log.entity';
import { CopilotFieldMapping } from '../database/entities/copilot-field-mapping.entity';
import { AnthropicProxyController } from './anthropic-proxy.controller';
import { OpenAIProxyController } from './controllers/openai-proxy.controller';
import { GeminiProxyController } from './controllers/gemini-proxy.controller';
import { AnthropicProxyService } from './anthropic-proxy.service';
import { ProxyConfigService } from './config/proxy.config';
import { ConfigManagementService } from './services/config-management.service';
import { ForwardingService } from './services/forwarding.service';
import { EnhancedForwardingService } from './services/enhanced-forwarding.service';
import { MultiApiConfigService } from './services/multi-api-config.service';
import { TokenManagerService } from './services/token-manager.service';
import { CopilotRequestLoggerService } from './services/copilot-request-logger.service';
import { FieldDiffTrackerService } from './services/field-diff-tracker.service';
import { CopilotLogsController } from './controllers/copilot-logs.controller';
import { CopilotAdapter } from './adapters/copilot.adapter';
import { AnthropicCopilotAdapter } from './adapters/anthropic-copilot.adapter';
import { OpenAICopilotAdapter } from './adapters/openai-copilot.adapter';
import { GeminiCopilotAdapter } from './adapters/gemini-copilot.adapter';
import { AdapterRegistryService } from './core/adapter-registry.service';
import { GenericForwardingService } from './core/generic-forwarding.service';

@Module({
  imports: [
    HttpModule.register({
      timeout: 30000,
      maxRedirects: 3,
    }),
    ConfigModule,
    TypeOrmModule.forFeature([CopilotConfig, CopilotRequestLog, CopilotFieldMapping])
  ],
  controllers: [
    AnthropicProxyController,
    OpenAIProxyController,
    GeminiProxyController,
    CopilotLogsController
  ],
  providers: [
    // 核心服务
    AnthropicProxyService,
    ProxyConfigService,
    ConfigManagementService,
    TokenManagerService,
    CopilotRequestLoggerService,
    FieldDiffTrackerService,
    
    // 转发服务 - 新旧并存
    ForwardingService, // 保留向后兼容
    EnhancedForwardingService, // 新的增强服务
    GenericForwardingService, // 通用转发核心
    MultiApiConfigService, // 多API配置管理
    AdapterRegistryService,
    
    // 适配器 - 新旧并存
    CopilotAdapter, // 保留向后兼容
    AnthropicCopilotAdapter, // 新的 Anthropic 适配器
    OpenAICopilotAdapter, // OpenAI 适配器示例
    GeminiCopilotAdapter, // Gemini 适配器
    
    {
      provide: 'CONFIG_MANAGEMENT_INJECTION',
      useFactory: (anthropicService: AnthropicProxyService, configService: ConfigManagementService) => {
        anthropicService.setConfigManagementService(configService);
        return anthropicService;
      },
      inject: [AnthropicProxyService, ConfigManagementService],
    }
  ],
  exports: [
    AnthropicProxyService,
    ProxyConfigService,
    ConfigManagementService,
    ForwardingService,
    EnhancedForwardingService,
    MultiApiConfigService,
    TokenManagerService
  ]
})
export class AnthropicProxyModule implements OnModuleInit {
  constructor(
    private readonly adapterRegistry: AdapterRegistryService,
    private readonly anthropicCopilotAdapter: AnthropicCopilotAdapter,
    private readonly openaiCopilotAdapter: OpenAICopilotAdapter,
    private readonly geminiCopilotAdapter: GeminiCopilotAdapter
  ) {}

  /**
   * 模块初始化时注册所有适配器
   */
  async onModuleInit() {
    // 注册适配器到注册表
    this.adapterRegistry.register(this.anthropicCopilotAdapter);
    this.adapterRegistry.register(this.openaiCopilotAdapter);
    this.adapterRegistry.register(this.geminiCopilotAdapter);
    
    console.log('🚀 Anthropic Proxy Module initialized with multi-API support');
    console.log('📋 Registered adapters:');
    
    const routes = this.adapterRegistry.getSupportedRoutes();
    routes.forEach(route => {
      console.log(`   - ${route.provider} → ${route.target}`);
    });
    
    console.log('🔗 Available API endpoints:');
    console.log('   - Anthropic API: /v1/* (original)');
    console.log('   - OpenAI API: /openai/v1/*');
    console.log('   - Gemini API: /gemini/v1/*');
  }
}